//
//  CadreManagementViewController.m
//  Againstpoor
//
//  Created by 辰领科技 on 16/11/7.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "CadreManagementViewController.h"
#import "CadreManagementTableViewCell.h"
#import "TimeTableViewCell.h"
#import "ManagementDetailsViewController.h"

static NSString * Identifier = @"tableViewCell";

@interface CadreManagementViewController ()
<UITableViewDelegate,UITableViewDataSource> {
    NSUInteger count;
    NSInteger _totle;
}

@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITableView *timeTableView;
@property (weak, nonatomic) IBOutlet UIButton *timescreeningButton;
@property (weak, nonatomic) IBOutlet UIButton *BGbutton;
@property (strong, nonatomic) NSMutableArray *array;

@end

@implementation CadreManagementViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _BGbutton.alpha = 0.0f;
    _timeTableView.frame = flexibleFrame(CGRectMake(0, 94, 320, 0), NO);
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    count = 0;
    _pageNO = 1;
    _array = [NSMutableArray array];
    
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.timeTableView.delegate = self;
    self.timeTableView.dataSource = self;
}
- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getmanagementList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.array.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getmanagementList];
        });
    }
}

#pragma mark - 驻村干部管理
- (void)getmanagementList {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:[NSString stringWithFormat:@"%d",_pageNO] forKey:@"page"];
    [dic setObject:[NSString stringWithFormat:@"%d",PageSize] forKey:@"pageSize"];
    if (count == 0) {
        [dic setObject:@"" forKey:@"type"];
    } else if (count == 1) {
        [dic setObject:@"1" forKey:@"type"];
    } else if (count == 2) {
        [dic setObject:@"3" forKey:@"type"];
    }else if (count == 3) {
        [dic setObject:@"5" forKey:@"type"];
    }
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_reportMessag withHttpType:@"POST" withTag:F_F_reportMessag];
}

#pragma mark - 搜索
- (IBAction)search:(id)sender {
}
#pragma mark - 时间筛选
- (IBAction)time:(UIButton *)sender {
    _timescreeningButton.selected = !_timescreeningButton.selected;
    if (_timescreeningButton.selected) {
        [UIView animateWithDuration:0.5 animations:^{
            _timeTableView.frame = flexibleFrame(CGRectMake(0, 94, 320, 45*4), NO);
            _BGbutton.alpha = 1;
        }];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            _timeTableView.frame = flexibleFrame(CGRectMake(0, 94, 320, 0), NO);
            _BGbutton.alpha = 0.0f;
        }];
    }
}
- (IBAction)hidden:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        _timeTableView.frame = flexibleFrame(CGRectMake(0, 94, 320, 0), NO);
        _BGbutton.alpha = 0.0f;
    }];
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        return _array.count;
    } else {
        return 4;
    }
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        return 46*VerticalRatio();
    } else {
        return 45*VerticalRatio();
    }
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        CadreManagementTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:Identifier];
        if (cell == nil) {
            cell= [[CadreManagementTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        NSDictionary *dic = _array[indexPath.row];
        cell.nameLabel.text = [Common stringFromData:dic[@"NAME"]];
        NSString * number = [NSString stringWithFormat:@"%@",dic[@"COUNT"]];
        NSMutableAttributedString * strOne = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@次",number]];
        [strOne addAttribute:NSForegroundColorAttributeName value:kGetColor(182, 2, 1) range:NSMakeRange(0, number.length)];
        [cell.numberLabel setAttributedText:strOne];
        cell.timeLabel.text = [Common stringFromData:dic[@"TIME"]];
        
        return cell;
    } else {
        TimeTableViewCell *cell = [self.timeTableView dequeueReusableCellWithIdentifier:@"Cell"];
        if (cell == nil) {
            cell= [[TimeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        
        cell.label.textColor = kGetColor(62, 62, 62);
        cell.label.text = [NSString stringWithFormat:@"%@",self.timeArray[indexPath.row]];
        cell.button.selected = NO;
        if (indexPath.row == count) {
            cell.label.textColor = kGetColor(0, 82, 164);
            cell.button.selected = YES;
        }

        return cell;
    }
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
        ManagementDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ManagementDetails"];
        page.ACCID = [Common stringFromData:_array[indexPath.row][@"ACCID"]];
        page.number = [Common stringFromData:_array[indexPath.row][@"COUNT"]];
        page.name = [Common stringFromData:_array[indexPath.row][@"NAME"]];
        [[Common getNavigation]pushViewController:page];
    } else {
        count = indexPath.row;
        [_timescreeningButton setTitle:self.timeArray[count] forState:UIControlStateNormal];
        [self.timeTableView reloadData];
        [UIView animateWithDuration:0.5 animations:^{
            _timeTableView.frame = flexibleFrame(CGRectMake(0, 94, 320, 0), NO);
            _BGbutton.alpha = 0.0f;
        }];
        [self.tableView.header beginRefreshing];
    }
    
}

#pragma mark - Custom Accessor
- (NSArray *)timeArray {
    NSArray *timeArray;
    if (!timeArray) {
        timeArray = @[@"所有时间",@"近一个月",@"近三个月",@"近五个月"];
    }
    return timeArray;
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    if (tag==F_F_reportMessag) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.array removeAllObjects];
                }
                
                NSArray *arr = database[@"rows"];
                for (id entity in arr) {
                    [self.array addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
            });
        }else  {
            
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    [self dismissWaitDialog];
    
    
}



@end
